package com.appengine.news.ui.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;

import com.appengine.news.entity.RssFeedEntity;
import com.appengine.news.ui.model.ManageModel;
import com.google.appengine.api.datastore.Text;

/**
 * Manage page controller
 * @author Aliaksandr_Spichakou
 *
 */
public class ManageController extends AbstractUIController{
	/**
	 * 
	 */
	private static final long serialVersionUID = 9177626704241794943L;
	private static final Logger log = Logger.getLogger(ManageController.class
			.getName());	
	private List<ManageModel> model = new ArrayList<ManageModel>();
	public ManageController(HttpServletRequest request) {	
		super(request);
	}
	
	@Override
	public void doJob() {
		log.entering(ManageController.class.getName(), "doJob");
		fillModel();	
		log.entering(ManageController.class.getName(), "doJob");
	}	
	
	/**
	 * Fill model for manage page
	 */
	private void fillModel()
	{
		log.entering(ManageController.class.getName(), "fillModel");		
		final PersistenceManager pm = getPersistenceManager();
		final String query = "select from " + RssFeedEntity.class.getName();
		final List<RssFeedEntity> feeds = (List<RssFeedEntity>) pm.newQuery(query).execute();
		for (RssFeedEntity feed : feeds) {
			final ManageModel m = new ManageModel();
			final Text subtitle = feed.getSubtitle();
			final Text title = feed.getTitle();			
			if(subtitle!=null)
			{
				final String subtitleTxt = subtitle.getValue();
				m.setSubtitleTxt(subtitleTxt);
			}			
			if(title!=null)
			{
				final String titleStr = title.getValue();
				m.setTitle(titleStr);
			}
			m.setId(feed.getId());
			m.setLastUpdate(feed.getLastUpdate());
			
			model.add(m);
		}
		log.exiting(ManageController.class.getName(), "fillModel");
	}
	/**
	 * Get model
	 * @return
	 */
	public List<ManageModel> getModel() {
		return model;
	}
}
